<template>
  <div class="tree-wrap">
    <el-tree
      :load="loadNode"
      lazy
      v-bind="$attrs"
      :expand-on-click-node="expandOnClickNode"
      :props="defaultProps"
      highlight-current
      check-on-click-node
      node-key="id"
      @node-click="handleNodeClick"
    >
      <template #default="{node, data}">
        <div class="node">
          <i style="color: #1890ff" class="el-icon-office-building" v-if="node.level === 1" />
          <i style="color: #1890ff" class="el-icon-school" v-else-if="node.level === 2" />
          <i style="color: #1890ff" class="el-icon-film" v-else-if="node.level === 3" />
          <i style="color: #1890ff" class="el-icon-house" v-else-if="node.level === 4" />
          <span>{{data.name}}</span>
        </div>
      </template>
    </el-tree>
  </div>
</template>
<script>
const level = {
  0: "",
  1: "area",
  2: "build",
  3: "floor",
  4: "room"
};
import { roomTree } from "@/api/base/room";
export default {
  name: "RoomTree",
  props: {
    value: Object,
    expandOnClickNode: {
      type: Boolean,
      default: false
    }
  },
  model: {
    prop: "value", // 指定 v-model 要绑定的参数叫什么名字，来自于 props 中定义的参数
    event: "change" // 指定要触发的事件名字，将被用于 $emit
  },
  data() {
    return {
      loading: false,
      data: [],
      defaultProps: {
        children: "children",
        label: "name",
        isLeaf: "leaf"
      },
      node: null
    };
  },
  computed: {
    input: {
      // 这里的计算属性使用了 getter、setter，可以简化代码
      // 可参见链接 https://cn.vuejs.org/v2/guide/computed.html#%E8%AE%A1%E7%AE%97%E5%B1%9E%E6%80%A7%E7%9A%84-setter
      get() {
        return this.value;
      },
      set(val) {
        this.$emit("change", val); // 触发
      }
    }
  },
  watch: {
    node: {
      immediate: true,
      deep: true,
      handler(val) {
        if(this.node?.childNodes?.length) {
          let nodedata = this.node.childNodes[0];
          nodedata.expanded = true;
          nodedata.loadData();
        }
      }
    }
  },
  methods: {
    loadNode(node, resolve) {
      if (node.level === 0) {
        this.node = node;
      } 
      roomTree({
        id: node?.data?.id || "",
        name: level[node.level+1]
      }).then(response => {
        resolve(response.data.sort((i1, i2) => (i1.name > i2.name ? 1 : -1)));
      });
    },
    getList() {
      this.loading = true;
      roomTree().then(response => {
        this.data = response.data.sort((i1, i2) =>
          i1.name > i2.name ? 1 : -1
        );
        this.loading = false;
      });
    },
    handleNodeClick(data, node, com) {
      this.$emit("change", {
        id: data.id,
        level: node.level,
        data: data,
        name: level[node.level]
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.tree-wrap {
  padding-right: 10px;
  max-height: 100%;
  overflow-y: auto;
  margin-right: 10px;
  border-right: 1px solid whitesmoke;
  width: 220px;
}
.node {
  font-size: 14px;
}
</style>